"""
Kafka相关API路由
"""
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query
from backend.models.kafka_models import (
    KafkaConnectionConfig, TopicInfo, PartitionInfo, 
    MessageRequest, MessageResponse, BatchMessageRequest, ConnectionStatus
)
from backend.models.response_models import BaseResponse, ErrorResponse
from backend.services.kafka_service import kafka_service
from backend.services.websocket_service import websocket_manager
from backend.utils.exceptions import (
    KafkaConnectionException, KafkaTopicException, 
    KafkaMessageException, KafkaAuthenticationException
)

router = APIRouter(prefix="/kafka", tags=["Kafka"])

@router.post("/test-connection", response_model=BaseResponse[ConnectionStatus])
async def test_connection(config: KafkaConnectionConfig):
    """测试Kafka连接"""
    try:
        status = kafka_service.test_connection(config)
        
        # 通过WebSocket通知连接状态
        await websocket_manager.send_connection_status(
            connected=status.connected,
            bootstrap_servers=config.bootstrap_servers
        )
        
        return BaseResponse(
            success=status.connected,
            message="连接测试成功" if status.connected else "连接测试失败",
            data=status
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"连接测试失败: {str(e)}"
        )

@router.post("/connect", response_model=BaseResponse[ConnectionStatus])
async def connect_kafka(config: KafkaConnectionConfig):
    """连接到Kafka集群"""
    try:
        status = kafka_service.connect(config)
        
        # 通过WebSocket通知连接状态
        await websocket_manager.send_connection_status(
            connected=status.connected,
            bootstrap_servers=config.bootstrap_servers
        )
        
        return BaseResponse(
            success=True,
            message="连接成功",
            data=status
        )
        
    except KafkaConnectionException as e:
        await websocket_manager.send_connection_status(
            connected=False,
            bootstrap_servers=config.bootstrap_servers
        )
        raise HTTPException(
            status_code=400,
            detail=e.message
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"连接失败: {str(e)}"
        )

@router.post("/disconnect", response_model=BaseResponse[None])
async def disconnect_kafka():
    """断开Kafka连接"""
    try:
        bootstrap_servers = kafka_service.connection_config.bootstrap_servers if kafka_service.connection_config else None
        kafka_service.disconnect()
        
        # 通过WebSocket通知连接状态
        await websocket_manager.send_connection_status(
            connected=False,
            bootstrap_servers=bootstrap_servers
        )
        
        return BaseResponse(
            success=True,
            message="连接已断开",
            data=None
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"断开连接失败: {str(e)}"
        )

@router.get("/status", response_model=BaseResponse[ConnectionStatus])
async def get_connection_status():
    """获取连接状态"""
    try:
        status = kafka_service.get_connection_status()
        
        return BaseResponse(
            success=True,
            message="获取连接状态成功",
            data=status
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取连接状态失败: {str(e)}"
        )

@router.get("/topics", response_model=BaseResponse[List[TopicInfo]])
async def get_topics():
    """获取所有Topic"""
    try:
        topics = kafka_service.get_topics()
        
        return BaseResponse(
            success=True,
            message=f"获取Topic列表成功，共{len(topics)}个Topic",
            data=topics
        )
        
    except KafkaConnectionException as e:
        raise HTTPException(
            status_code=400,
            detail=e.message
        )
    except KafkaTopicException as e:
        raise HTTPException(
            status_code=400,
            detail=e.message
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取Topic列表失败: {str(e)}"
        )

@router.get("/topics/{topic_name}", response_model=BaseResponse[TopicInfo])
async def get_topic_info(topic_name: str):
    """获取特定Topic信息"""
    try:
        topics = kafka_service.get_topics()
        
        # 查找指定的Topic
        target_topic = None
        for topic in topics:
            if topic.name == topic_name:
                target_topic = topic
                break
        
        if not target_topic:
            raise HTTPException(
                status_code=404,
                detail=f"Topic '{topic_name}' 不存在"
            )
        
        return BaseResponse(
            success=True,
            message=f"获取Topic信息成功: {topic_name}",
            data=target_topic
        )
        
    except HTTPException:
        raise
    except KafkaConnectionException as e:
        raise HTTPException(
            status_code=400,
            detail=e.message
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取Topic信息失败: {str(e)}"
        )

@router.get("/topics/{topic_name}/partitions", response_model=BaseResponse[List[PartitionInfo]])
async def get_topic_partitions(topic_name: str):
    """获取Topic分区信息"""
    try:
        partitions = kafka_service.get_topic_partitions(topic_name)
        
        return BaseResponse(
            success=True,
            message=f"获取Topic分区信息成功: {topic_name}",
            data=partitions
        )
        
    except KafkaConnectionException as e:
        raise HTTPException(
            status_code=400,
            detail=e.message
        )
    except KafkaTopicException as e:
        raise HTTPException(
            status_code=404,
            detail=e.message
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取Topic分区信息失败: {str(e)}"
        )

@router.post("/send", response_model=BaseResponse[MessageResponse])
async def send_message(request: MessageRequest):
    """发送消息到Kafka"""
    try:
        response = kafka_service.send_message(request)
        
        return BaseResponse(
            success=True,
            message=f"消息发送成功到Topic: {request.topic}",
            data=response
        )
        
    except KafkaConnectionException as e:
        raise HTTPException(
            status_code=400,
            detail=e.message
        )
    except KafkaMessageException as e:
        raise HTTPException(
            status_code=400,
            detail=e.message
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"消息发送失败: {str(e)}"
        )

@router.post("/send/batch", response_model=BaseResponse[List[MessageResponse]])
async def send_batch_messages(request: BatchMessageRequest):
    """批量发送消息"""
    try:
        responses = kafka_service.send_batch_messages(request.topic, request.messages)
        
        success_count = sum(1 for r in responses if r.success)
        
        return BaseResponse(
            success=success_count > 0,
            message=f"批量发送完成: {success_count}/{len(responses)} 成功",
            data=responses
        )
        
    except KafkaConnectionException as e:
        raise HTTPException(
            status_code=400,
            detail=e.message
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"批量发送失败: {str(e)}"
        ) 